'use strict'
const express = require('express');
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');

const util = require('../util');
const config = require('../config');


const router = express.Router();
const logger = util.logger;

const PULL_BOOK = './shell/pull-book.sh'
const COMP_BOOK = './shell/comp-book.sh'
const PUBLIST_BOOK = './shell/publish-book.sh'


router.get('/test', (req, res) => {
  res.end('success')
})

/**
 * book 自动部署
 */
const publishBook = async (body) => {
  let pullOut, buildOut, pubOut, err;
  let mail = {
    to: process.env.DOCS_PUBLISH_MODULE === 'proc' ? config.manager.proc : config.manager.dev
  }
  try{
    //git pull
    pullOut = await util.runShell(PULL_BOOK)
    //gitbook build
    buildOut = await util.runShell(COMP_BOOK)
    //mv _book
    pubOut = await util.runShell(PUBLIST_BOOK)
    //send mail
    mail.subject = `jufan-wiki 有更新，提交人：${body.user_name}，项目：${body.repository.name}`

  }catch(e){
    err = e;
    logger.error('auto publish book error: ', e);
    //send mail
    mail.subject = `jufan-wiki 更新失败, 提交人:${body.user_name}，错误:${e.message}`
  }
  mail.text = `
======> 更新 repository
${pullOut && util.out2String(pullOut.stdout)}
------> 警告
${pullOut && pullOut.stderr}
======> 构建 book
${buildOut && buildOut.stdout}
------> 警告
${buildOut && buildOut.stderr}
======> 部署 book
${pubOut && pubOut.stdout}
------> 警告
${pubOut && pubOut.stderr}
======> 提交说明
${JSON.stringify(body, null, 2)}
======> 异常:
${err ? JSON.stringify(err, null, 2).replace(/\\n/g, '\n') : '无'}
`
  //send mail
  logger.debug('mail text: %s', mail.text)
  sendMail(mail)
}

/**
 * 发送邮件
 */
const sendMail = (mail) => {
  logger.debug('send mail: ', mail);
  let transport = nodemailer.createTransport(config.mail, { from: 'jufan <zzu_laboratory@163.com>' });   //发送邮件的相关参数
  return new Promise((suc, fail) => {
    transport.sendMail(mail, (error, message) => {
      if (error){
        fail(error);
      }else{
        suc(message);
      }
    })
  });
};

router.post('/push', (req, res) => {
  let body = req.body;
  logger.info('push data: ', body);
  logger.debug('config self: ', config.hooks_book);
  if (body.password === config.hooks_book.password
    && body.ref === config.hooks_book.ref) {
    logger.debug('开始更新..')

    //运行自动更新脚本,不需要同步执行
    publishBook(body);
  }
  res.end('success');
});

module.exports = router;